package com.sunwayworld.dev.core.generate;

import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import com.sunwayworld.dev.io.freemarker.GenerateUtils;

public class GenerateFile {

	private String srcPath;

	private String vmPath;

	private Map context = new HashMap();

	public GenerateFile(String vmpath, String srcPath) {

		this.vmPath = vmpath;
		this.srcPath = srcPath.replace('/', File.separatorChar);;
	}

	public void generateCode() {
		try {

			GenerateUtils gf = new GenerateUtils();

			gf.generate(vmPath, srcPath, context);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@SuppressWarnings("unchecked")
	public void putContext(String key, Object object) {
		context.put(key, object);
	}

	public void putContext(Object object) {
		copyProperties(object, context);
	}

	@SuppressWarnings("unchecked")
	private void copyProperties(Object provide, Map context) {

		if (provide == null || context == null)
			return;
		Field[] fields = provide.getClass().getFields();
		for (int i = 0; i < fields.length; i++) {
			String fieldName = fields[i].getName();

			try {
				Object temp = fields[i].get(provide);
				if (temp != null) {
					context.put(fieldName, temp);
				}
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}

	public String getSrcPath() {
		return srcPath;
	}

	public void setSrcPath(String srcPath) {
		this.srcPath = srcPath;
	}
}
